package com.zdy.today.activity;

import android.Manifest;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieDrawable;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.orhanobut.logger.Logger;
import com.zdy.today.R;
import com.zdy.today.base.BaseActivity;
import com.zdy.today.dialog.TipDialog;
import com.zdy.utils.Utils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


/**
 * Created by jsb-cpyy on 2017/3/13.
 */
@RuntimePermissions
public class FileDownLoadActivity extends BaseActivity {
    String url = "http://imtt.dd.qq.com/16891/2643996B54BA5FAACEEEAD9B07AF3184.apk?fsname=com.bj.zhidian.wuliu_1.3.0_7.apk&csr=1bbd";
    //    String url = "http://zdy-android.oss-cn-hangzhou.aliyuncs.com/zdwl/zdwl_1.2.0_6.apk";
    @BindView(R.id.number_progress_bar)
    NumberProgressBar number_progress_bar;
    @BindView(R.id.tv_msg)
    TextView tv_msg;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.animation_view)
    LottieAnimationView animation_view;

    @Override
    protected void init() {
        String md5 = Utils.md5(new File(path));
        if (!TextUtils.isEmpty(md5))
            tv_msg.setText(md5);
        Logger.d("completed md5是" + md5);
        LottieDrawable drawable = new LottieDrawable();
        img.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        img.setImageDrawable(drawable);
        LottieComposition.Factory.fromAssetFileName(this, "diandongche.json", (composition) -> {
            drawable.setImagesAssetsFolder("imge/");
            drawable.setScale(0.5f);
            drawable.loop(true);
            drawable.setComposition(composition);
//            drawable.setScale(0.2f);
            drawable.playAnimation();
        });
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                drawable.cancelAnimation();
//            }
//        }, 5000);
    }

    @Override
    protected String setTitle() {
        return "下载测试";
    }

    @Override
    protected int getResourceId() {
        return R.layout.activity_file_down_load;
    }

    TipDialog tipDialog;

    @OnClick({R.id.bt_down_Load, R.id.bt_anim})
    public void onClicks(View v) {
        switch (v.getId()) {
            case R.id.bt_anim://动画

                break;
            case R.id.bt_down_Load://下载
                if (tipDialog == null)
                    tipDialog = TipDialog.createTipDialog(this, "发现新版本", "1,版本号v1.2.0\n2,版本大小6.90MB");
                tipDialog.setCancelable(false);
                tipDialog.setCanceledOnTouchOutside(false);
                tipDialog.getNumber_progress_bar().setVisibility(View.GONE);
                tipDialog.setOnSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        tipDialog.getNumber_progress_bar().setVisibility(View.VISIBLE);
                        tipDialog.setSingleBtnText("下载中...");
                        tipDialog.setOnSingleBtnListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if ("下载完成".equals(tipDialog.getSingleBtnText()))
                                    Utils.install(FileDownLoadActivity.this, new File(path), false);
                            }
                        });
                        FileDownLoadActivityPermissionsDispatcher.createFileDirWithCheck(FileDownLoadActivity.this);
                    }
                });
                tipDialog.show();
                break;
        }
    }

    String path = Utils.createFilePath("apk") + "zdwl.apk";

    private void downLoad() {
        File file = new File(path);
        if (file.exists())
            file.delete();
        FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Logger.d("pending soFarBytes=" + soFarBytes + "totalBytes=" + totalBytes);
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        Logger.d("connected soFarBytes=" + soFarBytes + " totalBytes=" + totalBytes + " etag=" + etag + " isContinue=" + isContinue);
                        number_progress_bar.setMax(totalBytes);
                        tipDialog.getNumber_progress_bar().setMax(totalBytes);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Logger.d("progress soFarBytes=" + soFarBytes + " totalBytes=" + totalBytes);
                        number_progress_bar.setProgress(soFarBytes);
                        tipDialog.getNumber_progress_bar().setProgress(soFarBytes);
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        Logger.d("blockComplete");
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        Logger.d("retry");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Logger.d("completed");
                        String md5 = Utils.md5(new File(path));
                        if (!TextUtils.isEmpty(md5))
                            Logger.d("completed md5是" + md5);
                        tipDialog.setSingleBtnText("下载完成");
                        number_progress_bar.setProgress(number_progress_bar.getMax());
                        tipDialog.getNumber_progress_bar().setProgress(number_progress_bar.getMax());
                        Utils.install(FileDownLoadActivity.this, file, false);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Logger.d("paused soFarBytes=" + soFarBytes + " totalBytes=" + totalBytes);
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Logger.d("error");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        Logger.d("warn");
                    }
                }).start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FileDownLoadActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void createFileDir() {
        downLoad();
    }
}
